<template>
	<view>
		<view
			class="border-f2 pd20 rel br10 backf"
			:class="type ? 'border-top-0' : ''"
		>
			<!-- <textarea :placeholder="placeholder" :value="remark" class="f32 g3 textarea" disabled @input="textareaInput"></textarea> -->
			<view class="mt20 df jss" v-if="audioFilePath !== ''">
				<view class="w80 rel">
					<view @click="playBtn()" class="audio-bg">
						<view class="audio-box df ac">
							<!-- <image :src="yuying" class="record-img"></image> -->
							<view>
								<view class="small"></view>
								<view
									class="middle"
									:class="
										playStatus === 0 ? 'stopanimate' : ''
									"
								></view>
								<view
									class="large"
									:class="
										playStatus === 0 ? 'stopanimate' : ''
									"
								></view>
							</view>
							<text class="ml20">{{ count }}秒</text>
						</view>
						<view v-if="voiceText" class="voice-text">{{
							voiceText
						}}</view>
					</view>
					<view class="record-close lh80"
						><uni-icons
							type="close"
							size="60rpx"
							color="#666666"
							@tap="delBtn"
						></uni-icons
					></view>
				</view>
			</view>
			<view class="mt50 tc rel">
				<button
					class="press-button w80"
					@longpress="longpressBtn()"
					@touchend="touchendBtn()"
					:disabled="
						(audioFilePath && audioFilePath !== '') || isDisabled
					"
				>
					{{ longPress == '1' ? '按住说话' : '说话中...' }}
				</button>
				<!-- 语音音阶动画 -->
				<view
					class="prompt-layer prompt-layer-1"
					v-if="longPress == '2'"
				>
					<view class="prompt-loader"
						><view
							class="em"
							v-for="(item, index) in 15"
							:key="index"
						></view
					></view>
					<text class="p">{{ '剩余：' + count + 's' }}</text>
					<text class="span">松手结束录音</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
const recorderManager = uni.getRecorderManager()
const innerAudioContext = uni.createInnerAudioContext()
var init // 录制时长计时器
var timer // 播放 录制倒计时
export default {
	name: 'diy-empty',
	emits: ['upload'],
	props: {
		context: {
			type: String,
			value: '',
		},
		voliceTime: {
			type: Number,
			value: '',
		},
		audioUrl: {
			type: String,
			value: '',
		},
		clear: {
			type: Boolean,
			value: false,
			default: false,
		},
		placeholder: {
			type: String,
			default: '使用语音输入',
		},
		isDisabled: {
			type: Boolean,
			value: false,
			default: false,
		},
		type: {
			type: String,
			value: '',
		},
	},
	data() {
		return {
			yuying: 'https://yilife-oss-online-public.oss-cn-hangzhou.aliyuncs.com/10000001/1015/ADMIN/lnz8ceecuqzyital7kfhp1wnp.png?timestamp=1676863826121',
			count: null, // 录制倒计时
			longPress: '1', // 1显示 按住说话 2显示 说话中
			delShow: false, // 删除提示框显示隐藏
			audioTime: 0, //录音时长
			duration: 60000, //录音最大值ms 60000/1分钟
			audioFilePath: '', //音频路径
			playStatus: 0, //录音播放状态 0:未播放 1:正在播放
			remark: '',
			voiceText: '',
			fileName: '',
			fileSize: 0,
		}
	},
	mounted() {
		console.log('子组件调用' + this.audioUrl)
		this.remark = this.context
		this.audioFilePath = this.audioUrl
		this.count = this.voliceTime
	},
	methods: {
		//输入框输入
		textareaInput(event) {
			this.remark = event.detail.value
			this.$emit('input', event.detail.value)
		},
		// 倒计时
		countdown(val) {
			let _then = this
			_then.count = Number(val)
			timer = setInterval(function () {
				if (_then.count > 0) {
					_then.count--
				} else {
					_then.longPress = '1'
					clearInterval(timer)
				}
			}, 1000)
		},
		// 长按录音事件
		longpressBtn() {
			let _that = this
			if (this.audioFilePath || this.isDisabled) {
				return false
			}
			uni.getSetting({
				success(res) {
					//判断是否第一次获取录音功能
					if (!res.authSetting['scope.record']) {
						//判断录音是否是开启状态false没开启就跳转到开启页面
						if (res.authSetting['scope.record'] === false) {
							uni.showModal({
								title: '提示',
								content: '您未授权录音，功能将无法使用',
								showCancel: true,
								confirmText: '授权',
								confirmColor: '#5374F7',
								success(res2) {
									if (res2.confirm) {
										uni.openSetting({
											success(res3) {},
										})
									}
								},
							})
						}
					} else if (res.authSetting['scope.record'] === true) {
						_that.longpressStartRecord()
					}
				},
			})
		},
		//开始录音
		longpressStartRecord() {
			this.longPress = '2'
			this.audioTime = 0
			this.countdown(60) // 倒计时
			clearInterval(init) // 清除定时器
			recorderManager.onStop((res) => {
				this.audioFilePath = res.tempFilePath
				this.recordingTimer(this.audioTime)
			})
			const options = {
				duration: this.duration, // 指定录音的时长，单位 ms
				sampleRate: 16000, // 采样率
				numberOfChannels: 1, // 录音通道数
				encodeBitRate: 96000, // 编码码率
				format: 'wav', // 音频格式，有效值 aac/mp3
				// frameSize: 64, // 指定帧大小，单位 KB
			}
			uni.setInnerAudioOption({
				obeyMuteSwitch: false,
			})

			this.recordingTimer()
			recorderManager.start(options)
			// 监听音频开始事件
			recorderManager.onStart((res) => {
				// console.log(res)
			})
		},
		// 长按松开录音事件
		touchendBtn() {
			let _that = this
			if (this.audioFilePath || this.isDisabled) {
				return false
			}
			this.longPress = '1'
			recorderManager.onStop((res) => {
				// console.log(res)
				// this.audioFilePath = res.tempFilePath
				_that.uploadRecord(res.tempFilePath)
			})
			this.recordingTimer(this.audioTime)
			clearInterval(timer)
			recorderManager.stop()
		},
		recordingTimer(time) {
			var that = this
			if (time == undefined) {
				// 将计时器赋值给init
				init = setInterval(function () {
					that.audioTime++
				}, 1000)
			} else {
				that.count = time
				clearInterval(init)
			}
		},
		// 删除录音
		delBtn() {
			// this.delShow = false;
			this.audioTime = 0
			this.audioFilePath = ''
			this.playStatus = 0
			innerAudioContext.stop()
			this.voiceText = ''
			this.remark = ''
			this.$emit('upload', {
				remark: '',
				time: 0,
				voiceText: '',
				fileName: '',
				fileSize: 0,
			})
			this.$emit('input', '')
		},
		// 播放
		playBtn() {
			innerAudioContext.src = this.audioFilePath

			//在ios下静音时播放没有声音，默认为true，改为false就好了。
			// innerAudioContext.obeyMuteSwitch = false
			//点击播放
			if (this.playStatus === 0) {
				this.playStatus = 1
				innerAudioContext.play()
				this.countdown(this.audioTime - (this.audioTime - this.count)) // 倒计时
			} else {
				this.playStatus = 0
				innerAudioContext.pause()
				clearInterval(timer)
			}
			//播放结束
			innerAudioContext.onEnded(() => {
				this.playStatus = 0
				innerAudioContext.stop()
				this.count = this.audioTime
				clearInterval(timer)
			})
		},
		// 上传文件
		uploadTextVolice(file) {
			return new Promise((resolve, reject) => {
				let _that = this
				uni.uploadFile({
					url:
						getApp().globalData.uploadDomain +
						'oss-web/oss/upload/file?asyn=false',
					filePath: file,
					name: 'file',
					header: {
						tenantId: uni.getStorageSync('orgId'),
						Authorization: uni.getStorageSync('token'),
						reqChannel: getApp().globalData.reqChannel,
					},
					success: (uploadFileRes) => {
						let res = JSON.parse(uploadFileRes.data)
						if (res.success) {
							let fileData = res.data
							_that.audioFilePath = fileData.url
							_that.fileName = fileData.fileName
							_that.fileSize = fileData.fileSize
							resolve()
						} else {
							uni.showToast({
								title: res.message ? res.message : '上传失败~',
								icon: 'error',
							})
						}
					},
				})
			})
		},
		//上传语音
		uploadRecord(file) {
			let _that = this
			_that.uploadTextVolice(file).then(() => {
				_that.voiceText = '语音转文字中...'
				// 语音转文字
				uni.uploadFile({
					url:
						getApp().globalData.uploadDomain +
						'oss-web/asr/xfReal/getRealWord',
					filePath: file,
					name: 'file',
					header: {
						tenantId: uni.getStorageSync('orgId'),
						Authorization: uni.getStorageSync('token'),
						reqChannel: getApp().globalData.reqChannel,
					},
					success: (realRes) => {
						// console.log(JSON.parse(realRes.data))
						let resData = JSON.parse(realRes.data).data || ''
						_that.voiceText = resData
						_that.remark = resData
						let voiceRemarks = {
							remark: _that.audioFilePath,
							time: _that.audioTime,
							voiceText: _that.voiceText,
							fileName: _that.fileName,
							fileSize: _that.fileSize,
						}
						_that.$emit('upload', voiceRemarks)
						_that.$emit('input', _that.remark)
					},
				})
			})
		},
	},
	watch: {
		clear(val) {
			if (val) {
				this.remark = ''
				this.audioFilePath = ''
			}
		},
		audioUrl() {
			this.remark = this.context
			this.audioFilePath = this.audioUrl
			this.count = this.voliceTime
		},
	},
}
</script>

<style scoped lang="scss">
.record-bd {
	min-height: 200rpx;
}
.textarea {
	width: 100%;
	height: 150rpx;
}
.br10 {
	border-radius: 10rpx;
}

.audio-bg {
	background-color: #c6e2ff;
	box-shadow: -6rpx 0 8px 1px rgba(0, 0, 0, 0.2);
	border-radius: 16rpx;
	position: relative;
	padding-left: 20rpx;
	padding-right: 10rpx;
}
.audio-box {
	height: 80rpx;
	/* line-height: 80rpx; */
}
.voice-text {
	border-top: 2rpx solid #ccc;
	padding: 20rpx 10rpx;
	font-size: 36rpx;
}

.audio-bg::before {
	content: '';
	position: absolute;
	border-top: 14rpx solid transparent;
	border-bottom: 14rpx solid transparent;
	border-left: 14rpx solid transparent;
	border-right: 14rpx solid #c6e2ff;
	left: -26rpx;
	top: 24rpx;
}

.record-img {
	width: 32rpx;
	height: 32rpx;
}

.record-close {
	position: absolute;
	width: 60rpx;
	height: 60rpx;
	right: -24rpx;
	top: -34rpx;
	z-index: 9;
}

.press-button {
	height: 70rpx;
	line-height: 70rpx;
	text-align: center;
	background-color: rgba(241, 248, 255, 1);
	color: rgba(58, 155, 255, 1);
	border-radius: 40rpx;
	font-size: 32rpx;
	padding: 0 8px;
	border: 1px solid rgba(58, 155, 255, 1);
	font-weight: 600;
}
.press-button::after {
	border: none !important;
}

.press-button[disabled]:not([type]) {
	color: #999999;
	background-color: #dcdff0;
	border: none !important;
}
/* 提示小弹窗 */
.prompt-layer {
	border-radius: 16rpx;
	background: #dcdff0;
	padding: 16rpx 32rpx;
	box-sizing: border-box;
	position: absolute;
	left: 50%;
	transform: translateX(-50%);
	z-index: 99;
}

.prompt-layer::after {
	content: '';
	display: block;
	border: 12rpx solid rgba(0, 0, 0, 0);
	border-top-color: #dcdff0;
	position: absolute;
	bottom: -20rpx;
	left: 50%;
	transform: translateX(-50%);
}

.prompt-layer-1 {
	font-size: 24rpx;
	width: 256rpx;
	text-align: center;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	top: -180rpx;
}

.prompt-layer-1 .p {
	color: #000000;
}

.prompt-layer-1 .span {
	color: rgba(0, 0, 0, 0.6);
}

.prompt-loader .em {
}

/* 语音音阶------------- */
.prompt-loader {
	width: 192rpx;
	height: 40rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 12rpx;
}

.prompt-loader .em {
	display: block;
	background: #333333;
	width: 2rpx;
	height: 10%;
	margin-right: 5rpx;
	float: left;
}

.prompt-loader .em:last-child {
	margin-right: 0px;
}

.prompt-loader .em:nth-child(1) {
	animation: load 2.5s 1.4s infinite linear;
}

.prompt-loader .em:nth-child(2) {
	animation: load 2.5s 1.2s infinite linear;
}

.prompt-loader .em:nth-child(3) {
	animation: load 2.5s 1s infinite linear;
}

.prompt-loader .em:nth-child(4) {
	animation: load 2.5s 0.8s infinite linear;
}

.prompt-loader .em:nth-child(5) {
	animation: load 2.5s 0.6s infinite linear;
}

.prompt-loader .em:nth-child(6) {
	animation: load 2.5s 0.4s infinite linear;
}

.prompt-loader .em:nth-child(7) {
	animation: load 2.5s 0.2s infinite linear;
}

.prompt-loader .em:nth-child(8) {
	animation: load 2.5s 0s infinite linear;
}

.prompt-loader .em:nth-child(9) {
	animation: load 2.5s 0.2s infinite linear;
}

.prompt-loader .em:nth-child(10) {
	animation: load 2.5s 0.4s infinite linear;
}

.prompt-loader .em:nth-child(11) {
	animation: load 2.5s 0.6s infinite linear;
}

.prompt-loader .em:nth-child(12) {
	animation: load 2.5s 0.8s infinite linear;
}

.prompt-loader .em:nth-child(13) {
	animation: load 2.5s 1s infinite linear;
}

.prompt-loader .em:nth-child(14) {
	animation: load 2.5s 1.2s infinite linear;
}

.prompt-loader .em:nth-child(15) {
	animation: load 2.5s 1.4s infinite linear;
}

@keyframes load {
	0% {
		height: 10%;
	}

	50% {
		height: 100%;
	}

	100% {
		height: 10%;
	}
}

/* 语音音阶-------------------- */
.prompt-layer-2 {
	top: -80rpx;
}

.prompt-layer-2 .text {
	color: rgba(0, 0, 0, 1);
	font-size: 24rpx;
}
.border-top-0 {
	border-top: 0rpx !important;
}
/* 语音录制结束---------------------------------------------------------------- */
</style>
